<template>
  <div class="m-auto max-w-200 text-left ">
    <h1 class="font-bold text-3xl mb-4">👌 挂诊群</h1>
    <Spin :spinning="baseState.loading">
      <Form text="left"
            ref="formRef"
            :rules="formRules"
            :model="formState" :label-col="labelCol">
        <FormItem label="挂诊顾客查询"
                  name="phone"
        >
          <InputSearch
            :disabled="step !== 1"

            v-model:value="formState.phone"
            enter-button="查询"
            placeholder="输入顾客手机号查询"
            @search="handleInputSearch"
          />
        </FormItem>
        <template v-if="step===2">
          <Alert v-if="baseState.loading" message="读取客户信息...." type="info"/>
          <FormItem name="Section" label="分诊科室">
            <Select v-model:value="formState.Section" :options="getSectionOptions"/>
          </FormItem>
          <FormItem name="FieldConsultantId" label="美学顾问">
            <Select v-model:value="formState.FieldConsultantId" :options="getFieldConsultantIdOptions"/>
          </FormItem>
          <FormItem name="RepresentativeId" label="客户代表">
            <Select v-model:value="formState.RepresentativeId" :options="getRepresentativeIdOptions"/>
          </FormItem>
          <FormItem name="CustIntention" label="客户意向描述">
            <Textarea v-model:value="formState.CustIntention"/>
          </FormItem>
          <FormItem class="text-right">
            <Button type="primary" @click="handleSubmit" :loading="baseState.loading">提交</Button>
            <Button style="margin-left: 10px" @click="handleClear">取消</Button>
          </FormItem>
        </template>
      </Form>
      <div v-if="step=== 1">
        <Alert v-if="baseState.first" message="输入顾客手机号后点击查询" type="info"/>
        <Alert v-else-if="baseState.loading" message="查询中...." type="info"/>
        <Card
          v-else-if="baseState.list.length"
          v-for="item in baseState.list" :key="item.value"
          :style="{ marginBottom: '20px'}"
          @click="handleClick(item)"
        >
          <template #title>
            <Checkbox :checked="selectItem?.value === item.value"/>
            {{ item['data-name'] }}
            <span  class="text-red-500">
              {{item['手机']}}
            </span>
          </template>
          <template #extra>
            <span class="font-bold">手机 :</span>
            {{ item['客户姓名'] }}
          </template>
          <p>
            <span class="font-bold">建档时间 :</span>
            {{ item['网电回访人'] }}
          </p>
          <p>
            <span class="font-bold">建档人 :</span>
            {{ item['建档人'] }}
          </p>
          <p>
            <span class="font-bold" v-if="item['预约类型']">客户代表 :</span>
            {{ item['预约类型'] }}
          </p><p>
            <span class="font-bold" v-if="item['客户代表']">美学顾问 :</span>
            {{ item['客户代表'] }}
          </p>
        </Card>
        <Alert v-else message="Ops! 查询结果为空." type="info"/>

        <div v-if="selectItem" class="text-center">
          <Button type="primary" :loading="baseState.loading" @click="finishFirstStep">领取预约单</Button>
        </div>
      </div>
    </Spin>
  </div>
</template>
<script setup>
import {FormItem, Form, InputSearch, Card, Checkbox, Button, Alert, Select, Textarea, Spin} from "ant-design-vue"
import {getReceptionNoteFormData, searchReceptionNote, showModal} from "../requests/method";
import {FieldReceptionNoteGetRecs, StoreFieldReceptionNoteCreate} from "../requests/index";

useHead({
  title: '预约单领取'
})
const labelCol = {style: {width: '150px'}};
const formRef = ref();
const formRules = {
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  FieldConsultantId: [
    {required: true, message: '请选择美学顾问', trigger: 'blur'},
  ],
  RepresentativeId: [
    {required: true, message: '请选择客户代表', trigger: 'blur'},
  ],
  Section: [
    {required: true, message: '请选择分诊科室', trigger: 'blur'},
  ],
  CustIntention: [
    {required: true, message: '请输入客户意向描述', trigger: 'blur'},
  ],


}
const formState = reactive({
  phone: '',
  Section: "",
  FieldConsultantId: "",
  RepresentativeId: "C482801F08034A78A689ABD100980CA0",
  CustIntention: "再消",
})
let defaultBaseState = {
  list: [],
  first: true,
  loading: false,
  formData: {},
  optionData: {},
};
const baseState = reactive({...defaultBaseState})
const step = ref(1);

const handleSubmit = async () => {
  if (baseState.loading) return;
  try {
    baseState.loading = true;
    let valid = await formRef.value.validate();
    console.log("valid", valid);
    if (!valid) return;

    const params = {
      CustId: baseState.formData.CustId,
      CustFamilyno: baseState.formData.CustFamilyno,
      refreshTabId: baseState.formData.refreshTabId,
      CustCardno: baseState.formData.CustCardno,
      CustName: baseState.formData.CustName,
      Phone: formState.phone,
      SEX: baseState.formData.SEX,
      oldSex: baseState.formData.oldSex,
      Age: baseState.formData.Age,
      oldAge: baseState.formData.Age,
      Birthday: baseState.formData.Birthday,
      oldBirth: baseState.formData.oldBirth,
      MediaSourceType: baseState.formData.MediaSourceType,
      MediaSource: baseState.formData.MediaSource,
      CustMedia: baseState.formData.CustMedia,
      Country: "0",
      Province: "610000",
      City: "610100",
      Area: "610101",
      Section: formState.Section,
      FieldConsultantIds: "1",
      FieldConsultantId: formState.FieldConsultantId,
      RepresentativeIds: "1",
      RepresentativeId: formState.RepresentativeId,
      CustIntention: formState.CustIntention,
      SerialNo: baseState.formData.SerialNo,
      CreatedBy: baseState.formData.CreatedBy,
      ReceptionEmpId: baseState.formData.ReceptionEmpId,
      ArrangeType: "1",
      ReceptionNo: baseState.formData.ReceptionNo,
      isFamily: baseState.formData.isFamily,
    }

    try {

      const response = await StoreFieldReceptionNoteCreate(params);
      if (response.data?.code === 0) {
        let data = JSON.parse(response.data.data);
        let msg = data.message;
        if (data.statusCode === "200") {
          showModal("提交成功~");
        } else {
          showModal(msg || "请检查提交内容.或截图联系管理员排查");
        }
        cacheParams();
      }
    } catch (e) {
      console.error('error', e)
      showModal(e.toString() || "请检查提交内容.或截图联系管理员排查");
    }
  } catch (e) {
    console.error('error', e)
  }
  baseState.loading = false;
}

const handleInputSearch = async () => {
  if (baseState.loading) return;
  baseState.loading = true;

  try {
    selectItem.value = null;
    if (baseState.first)
      baseState.first = false;

    let response = await searchReceptionNote(formState.phone);
    if (response.data?.code === 0) {
      baseState.list = parseBaseStateList(response.data.data.list);
    }
    console.log("response", response);
  } catch (e) {
    console.error("error", e);
  }
  baseState.loading = false;
}

const parseBaseStateList = (list) => {
  return list?.map(item => {
    item.is_new = item['手机'].includes('新客户');
    return item;
  }) || [];
}

const handleLoadFormData = async () => {
  if (baseState.loading) return;
  baseState.loading = true;

  try {
    let response = await getReceptionNoteFormData(formState.phone);
    if (response.data?.code === 0) {
      baseState.formData = response.data.data.form;
      baseState.optionData = response.data.data.options;
    }
    console.log("response", response);
  } catch (e) {
    console.error("error", e);
  }
  baseState.loading = false;
}

const selectItem = ref();
const handleClick = (item) => {
  selectItem.value = item;
}
const handleClear = () => {
  formRef.value.resetFields();
  step.value = 1;
  selectItem.value = null;
  Object.assign(baseState, defaultBaseState);
  getCacheParams();
}

const checkCustomerHasReception = async (id) => {
  if (baseState.loading) return;
  baseState.loading = true;
  let result = false;
  try {
    let response = await FieldReceptionNoteGetRecs({
      custid: id,
      enableReceptionWithoutorg: ''
    })
    result = !!response.data?.data?.list.length;
  } catch (e) {

  }
  baseState.loading = false;
  return result;
}

const finishFirstStep = async () => {
  const {value, onclick,客户代表:user} = selectItem.value;
  if (user === '公共池') {
    showModal("归属公共池不能预约","温馨提醒");
    return;
  }

  const match = (onclick?.match(/RadioClick\('([^']*)'\)/))?.[1];
  if (!match) {
    showModal("请检查手机号码","温馨提醒");
    return;
  }
  let res = await checkCustomerHasReception(match);
  if (!res) {
    showModal("顾客首次挂诊,请先在一楼现场预约","温馨提醒");
    return;
  }

  nextStep();
  formState.phone = value;
  await handleLoadFormData();
}

const nextStep = () => {
  step.value += 1;
}

const CACHE_KEY = "_previous_reception_params";
const cacheParams = (params = null) => {
  params = params || {...formState};
  localStorage.setItem(CACHE_KEY, JSON.stringify(params));
}
const getCacheParams = () => {
  let data = JSON.parse(localStorage.getItem(CACHE_KEY) || "{}");
  if (!data) return;

  formState.Section = data?.['Section'] || '';
  formState.CustIntention = data?.['CustIntention'] || '';
  formState.RepresentativeId = data?.['RepresentativeId'] || 'C482801F08034A78A689ABD100980CA0';
  formState.FieldConsultantId = data?.['FieldConsultantId'] || '';
}

const getSectionOptions = computed(() => {
  let obj = baseState.optionData?.Section || {};
  return Object.keys(obj).map((key) => ({label: obj[key], value: key}))
})


const getFieldConsultantIdOptions = computed(() => {
  let obj = baseState.optionData?.FieldConsultantId || {};
  return Object.keys(obj).map((key) => ({label: obj[key], value: key}))
})

const getRepresentativeIdOptions = computed(() => {
  let obj = baseState.optionData?.RepresentativeId || {};
  return Object.keys(obj).map((key) => ({label: obj[key], value: key}))
})

onMounted(() => {
  getCacheParams();
});
</script>
<style scoped>

</style>
